﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace dotNetInteropPlugin.CSharpMixingLibrary
{
    internal class PluginStateSaver
    {
        public const string ConfigSectionName = "ManagedPluginsList";

        public PluginStateSaver(PluginDev.IMAIMPConfigurationManager cfg)
        {
            inConfigWrk = cfg;
        }

        private PluginDev.IMAIMPConfigurationManager inConfigWrk;

        public void LoadSates(PluginInfoCollection plgCol)
        {
            if (!inConfigWrk.IsSectionExist(ConfigSectionName))
                return;

            foreach (PluginInformation pinf in plgCol)
            {
                if (inConfigWrk.ReadParameterInt32(ConfigSectionName, GetPluginNameID(pinf)) == 1)
                    pinf.Load();
                else
                    pinf.Unload();
            }
        }

        public void SaveStates(PluginInfoCollection plgCol)
        {
            inConfigWrk.RemoveSection(ConfigSectionName);

            foreach (PluginInformation pinf in plgCol)
            {
                if (pinf.IsLoaded)
                    inConfigWrk.WriteParameter(ConfigSectionName, GetPluginNameID(pinf), 1);
            }
        }

        private string GetPluginNameID(PluginInformation pinf)
        {
            string asm = pinf.PluginAssemblyName;
            int prtId = asm.IndexOf(',');
            if (prtId > 0)
                asm = asm.Substring(0, prtId);
            string clsNm = pinf.PluginClassName.Replace('.', '_');
            return asm + "_" + clsNm;
        }
    }
}
